<?php

namespace Drupal\shusy_vip\Entity;

use Drupal\shusy_vip\ViewsController\Traits\ShusyVipStatusTrait;
use Entity;

class ShusyVip extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $name;

  public $rebate = 0;

  public $amount = 0;

  public $sort = 0;

  public $is_default = 0;

  public $status = 0;

  use ShusyVipStatusTrait;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_vip');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }

    //检查是否设置为了默认
    if ($this->is_default == 1) {
      $jVipLevels = shusy_vip_load_multiple(FALSE, ['is_default' => 1]);
      if (!empty($jVipLevels)) {
        foreach ($jVipLevels as $jVipLevel) {
          if ($jVipLevel instanceof ShusyVip && $this->id != $jVipLevel->id) {
            $jVipLevel->is_default = 0;
            $jVipLevel->save();
          }
        }
      }
    }

    return parent::save();
  }

}
